<?php
namespace app\api\home;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\Controller;
use think\Exception;
use think\Log;

/**
 * 短信
**/
class Sms extends Controller
{

    public function index(){
        try {
            $client = self::createClient();
            $sendSmsRequest = new SendSmsRequest([
                "phoneNumbers" => '13713750445',  //发送的手机号码
                "signName" => '华云',  //签名
                "templateCode" => 'SMS_95375068',  //模板CODE
                //你注册账号的验证码:{#123446}:*
                "templateParam" => '{"code":"1234"}'  //这个根据你的模板信息来
            ]);

            $result = $client->sendSms($sendSmsRequest);
            if ($result->body->message === 'OK' && $result->body->code === 'OK') {
                return rsJson('',200,$result->body->message);
            }

            return rsJson('',500,$result->body->message);
        }
        catch (Exception $error) {
            (new Log())->error('短信发送失败'.$error->getMessage());
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient(){
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => \config('aly_config.accessKeyId'),
            // 您的 AccessKey Secret
            "accessKeySecret" => \config('aly_config.accessKeySecret')
        ]);
        // 访问的域名
        $config->endpoint = \config('aly_config.AliSmsEndpoint');
        return new Dysmsapi($config);
    }

}

